package com.yanchangapp.ui.activity.base;

import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.zxl.baselib.bean.response.BaseResponse;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.CheckUtils;
import com.zxl.baselib.util.Md5Utils;
import com.zxl.baselib.util.NetUtils;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.DisplayHelper;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.yanchangapp.R;
import com.yanchangapp.base.ApiRetrofit;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.ui.activity.BaseTimeTask;
import com.yanchangapp.ui.activity.BaseTimeTaskListener;
import com.yanchangapp.widget.VerificationSeekBar;

import java.util.Timer;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RegisterActivity extends BaseActivity implements BaseTimeTaskListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etCode)
    EditText etCode;
    @BindView(R.id.btnSendSms)
    Button btnSendSms;
    @BindView(R.id.etPassword)
    EditText etPassword;
    @BindView(R.id.ivSeePwd)
    ImageView ivSeePwd;
    @BindView(R.id.etPasswordSure)
    EditText etPasswordSure;
    @BindView(R.id.ivSeePwdSure)
    ImageView ivSeePwdSure;
    @BindView(R.id.etName)
    EditText etName;
    @BindView(R.id.etIdentify)
    EditText etIdentify;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.tvReturnLogin)
    TextView tvReturnLogin;
    @BindView(R.id.content)
    LinearLayout content;
    @BindView(R.id.llInfo)
    View mLlInfo;
    @BindView(R.id.sb_progress)
    VerificationSeekBar mSeekBar;
    @BindView(R.id.tvDes)
    TextView mTvDes;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.tvHasRead)
    TextView tvHasRead;
    @BindView(R.id.tvProtocol)
    TextView tvProtocol;
    private boolean isFirst = true;
    private int mButtonHeight;
    private ViewTreeObserver mTreeObserver;
    private ViewTreeObserver.OnGlobalLayoutListener mListener;
    private boolean mVertifyOk = false;
    private Timer mTimer;
    private int mCount;
    private boolean hasRead = true;
    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_register;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("新用户注册");
        buttonBeyondKeyboardLayout(content, tvReturnLogin);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

        // 滑块验证事件...
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getProgress() != seekBar.getMax()) {
                    seekBar.setProgress(0);
                } else {
                    mVertifyOk = true;
                    mSeekBar.setEnabled(false);
                    mTvDes.setText("验证通过");
                    Drawable drawable = ResHelper.getDrawable(R.mipmap.slider_success);
                    mSeekBar.setThumb(drawable);
                    mSeekBar.setThumbOffset(drawable.getMinimumWidth());
                    // 设置图片...
                }
            }
        });

        checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> hasRead = isChecked);

        tvHasRead.setOnClickListener(v -> checkbox.toggle());

        tvProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jumpToActivity(AccreditActivity.class);
            }
        });

    }

    @Override
    protected void onDestroy() {
        if (mListener != null && mTreeObserver != null && mTreeObserver.isAlive()) {
            mTreeObserver.removeOnGlobalLayoutListener(mListener);
        }

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroy();
    }

    @OnClick({R.id.ivToolbarNavigation,
            R.id.btnSendSms,
            R.id.btnLogin,
            R.id.tvReturnLogin,
            R.id.content,
            R.id.ivSeePwd,
            R.id.ivSeePwdSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivToolbarNavigation:
                finish();
                break;
            case R.id.btnSendSms:
                sendSms();
                break;
            case R.id.btnLogin:
                doRegister();
                break;
            case R.id.tvReturnLogin:
                finish();
                break;
            case R.id.content:
                KeyboardHelper.hideKeyboard(content);
                break;
            case R.id.ivSeePwd:
                actionChangeSee();
                break;
            case R.id.ivSeePwdSure:
                actionSureSee();
                break;
        }
    }

    /*
     * 密码点击事件(眼睛)
     */
    public void actionChangeSee() {
        if (etPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
            // 由可见变为不可见
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.hide_pwd);
        } else {
            // 由不可见变为可见
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.show_pwd);
        }
    }

    /*
     * 确定密码点击事件(眼睛)
     */
    public void actionSureSee() {
        if (etPasswordSure.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
            // 由可见变为不可见
            etPasswordSure.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivSeePwdSure.setImageResource(R.mipmap.hide_pwd);
        } else {
            // 由不可见变为可见
            etPasswordSure.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivSeePwdSure.setImageResource(R.mipmap.show_pwd);
        }
    }

    // 屏幕移动的事件...
    private void buttonBeyondKeyboardLayout(final View root, final View button) {
        // 监听根布局的视图变化
        // 获取内容布局在窗体的可视区域
        // 获取内容布局在窗体的不可视区域高度(被其他View遮挡的区域高度)
        // top = 48 = 24*2 即为去除状态栏之外的区域
        // 若不可视区域高度大于100，则键盘显示
        // 获取须顶上去的控件在窗体的坐标
        // 计算root滚动高度，使scrollToView在可见区域
        /* scrollTo并未改变原来的位置
         *  貌似OnLayout可以
         * */// 键盘隐藏
        mListener = () -> {
            Rect rect = new Rect();
            // 获取内容布局在窗体的可视区域
            root.getWindowVisibleDisplayFrame(rect);
            // 获取内容布局在窗体的不可视区域高度(被其他View遮挡的区域高度)
            // top = 48 = 24*2 即为去除状态栏之外的区域
            int rootInvisibleHeight = root.getHeight() - rect.bottom;
            // 若不可视区域高度大于100，则键盘显示
            if (rootInvisibleHeight > 100) {
                Log.e("focus", etCode.hasFocus() + " === " + etPhone.hasFocus());
                if (etCode.hasFocus() || etPhone.hasFocus()) {
                    return;
                }
                int[] location = new int[2];
                // 获取须顶上去的控件在窗体的坐标
                button.getLocationInWindow(location);
                // 计算root滚动高度，使scrollToView在可见区域
                /* scrollTo并未改变原来的位置
                 *  貌似OnLayout可以
                 * */
                int buttonHeight = button.getHeight() + location[1];
                // 判断登录按钮是否包含在可是区域内
                if (rect.bottom > buttonHeight) {
                    if (mListener != null && mTreeObserver.isAlive()) {
                        mTreeObserver.removeOnGlobalLayoutListener(mListener);
                    }
                    mListener = null;
                } else {
                    if (isFirst) {
                        mButtonHeight = (buttonHeight - rect.bottom + DisplayHelper.dp2Px(10));
                        isFirst = false;
                    }
                    Log.e("滑动", "滑动的高度 = " + mButtonHeight);
                    mLlInfo.scrollTo(0, mButtonHeight);
                }
            } else {
                // 键盘隐藏
                mLlInfo.scrollTo(0, 0);
                isFirst = true;
            }
        };
        mTreeObserver = root.getViewTreeObserver();
        mTreeObserver.addOnGlobalLayoutListener(mListener);
    }

    /*
     * 发送sms点击事件...
     */
    private void sendSms() {
        String mobile = etPhone.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            UIUtils.showToast("请输入手机号码");
            return;
        }
        if (!CheckUtils.isMobile(mobile)) {
            UIUtils.showToast("手机号格式错误");
            return;
        }

        netQuerySms(mobile);
        initTimer();
    }

    public void netQuerySms(String mobile) {
        ApiRetrofit.getInstance().getSms(mobile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS ||
                                baseResponse.getCode() == 203) {
                            UIUtils.showToast("短信发送成功");
                        } else {
                            reBackTimeTask();
                            UIUtils.showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {
                        UIUtils.showToast("短信发送失败");
                        reBackTimeTask();
                    }
                });
    }

    private void initTimer() {
        mCount = 60;
        // 设置发送按钮不可点击
        btnSendSms.setEnabled(false);
        if (mTimer == null) {
            mTimer = new Timer();
        }
        mTimer.schedule(new BaseTimeTask(this), 0, 1000);
    }

    @Override
    public void doTimeTask() {
        runOnUiThread(() -> {
            if (mCount > 0) {
                btnSendSms.setText(String.valueOf(mCount));
                mCount--;
            } else {
                mTimer.cancel();
                btnSendSms.setText("获取验证码");
                // 设置发送按钮可以点击...
                btnSendSms.setEnabled(true);
                mTimer = null;
            }
        });
    }

    public void reBackTimeTask() {
        mTimer.cancel();
        mTimer = null;
        btnSendSms.setText("获取验证码");
        // 设置发送按钮可以点击...
        btnSendSms.setEnabled(true);
    }

    /*
     * 注册的点击事件...
     */
    private void doRegister() {
        // 手机号码校验
        String mobile = etPhone.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            UIUtils.showToast("请输入手机号码");
            return;
        }
        if (!CheckUtils.isMobile(mobile)) {
            UIUtils.showToast("手机号格式错误");
            return;
        }

        // sms code校验
        String smsCode = etCode.getText().toString();
        if (TextUtils.isEmpty(smsCode)) {
            UIUtils.showToast("请输入验证码");
            return;
        }

        // 密码校验
        String password = etPassword.getText().toString();
        if (TextUtils.isEmpty(password)) {
            UIUtils.showToast("密码不能为空");
            return;
        }

        if (!CheckUtils.isPassword(password)){
            UIUtils.showToast("密码必须为6-16位数字或字母组合");
            return;
        }

        String nextPassword = etPasswordSure.getText().toString();
        if (TextUtils.isEmpty(nextPassword)) {
            UIUtils.showToast("确认密码不能为空");
            return;
        }

        if (!CheckUtils.isPassword(nextPassword)){
            UIUtils.showToast("确认密码必须为6-16位数字或字母组合");
            return;
        }

        if (!password.equals(nextPassword)) {
            UIUtils.showToast("您输入的密码不一致");
            return;
        }

        String name = etName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            UIUtils.showToast("请输入姓名");
            return;
        }

        String identity = etIdentify.getText().toString();
        if (TextUtils.isEmpty(identity)) {
            UIUtils.showToast("请输入身份证号码");
            return;
        }

        // 滑块校验...
        if (!mVertifyOk) {
            UIUtils.showToast("请拖动滑块验证");
            return;
        }

        if (!hasRead){
            UIUtils.showToast("请同意注册协议");
        }

        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }

        // 注册的网络请求事件...
        ApiRetrofit.getInstance().requestRegister(name, Md5Utils.md5(password), identity, mobile, smsCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS) {
                            finish();
                        } else {
                            UIUtils.showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {
                        UIUtils.showToast("注册失败");
                    }
                });
    }

}
